-module(handlerbase).

-export([handle_login/1,handle_other/1]).

-include("megaeyes.hrl").

wait_reply()->
    receive
	{insert,ok} ->
	    io:format("insert user ok~n");
	{lookup,error,Reason} ->
	    io:format("lookup user error ~w~n",[Reason]);
	{lookup,ok,Value} ->
	    io:format("lookup user ok~s~n",[Value]),
	    Value
    end.

handle_login(Request) ->
    RespBody = "<Message />",
    RespBodyBin = list_to_binary(RespBody),

    ?INFOSERVICE ! {self(),user,insert,Request#message.srcid,Request#message.body},
    ?INFOSERVICE ! {self(),user,lookup,Request#message.srcid},
    wait_reply(),

    Resp = <<(Request#message.ver):32/little,(size(RespBodyBin)):32/little,
	    (Request#message.id+1):32/little,(Request#message.no):32/little,0:32/little,
	    (RespBodyBin)/binary>>,
    
    io:format("Proc ~p Handle Request Version:~w Length:~w Id:~w No:~w SrcId:~s DestId:~s ~n", 
	      [self(),Request#message.ver,Request#message.len,Request#message.id,Request#message.no,
	       binary_to_list(Request#message.srcid),binary_to_list(Request#message.dstid)]),

    {response,Resp}.

handle_other(Request) ->
    Resp = <<(Request#message.ver):32/little,(size(Request#message.body)):32/little,
            (Request#message.id+1):32/little,(Request#message.no):32/little,0:32/little,
            (Request#message.body)/binary>>,
    
    io:format("Proc ~p Handle Request Version:~w Length:~w Id:~w No:~w SrcId:~s DestId:~s ~n",
              [self(),Request#message.ver,Request#message.len,Request#message.id,Request#message.no,
               binary_to_list(Request#message.srcid),binary_to_list(Request#message.dstid)]),
    
    {response,Resp}.


